<template>
  <div class="relative w-full h-[600px] overflow-hidden">
    <!-- 轮播容器 -->
    <div 
      ref="sliderRef"
      class="keen-slider h-full"
    >
      <div
        v-for="movie in movies"
        :key="movie.id"
        class="keen-slider__slide w-full h-full cursor-pointer"
        @click="goDetail(movie.id)"
      >
        <div class="relative w-full h-full bg-gradient-to-r from-background-800 to-background-700">
          <img :src="movie.coverUrl" :alt="movie.title" class="w-full h-full object-cover" />
          <div class="absolute inset-0 bg-gradient-to-t from-background-950/80 via-background-950/50 to-transparent"></div>
          <div class="absolute bottom-0 left-0 right-0 p-8 text-text-primary">
            <div class="max-w-6xl mx-auto">
              <div class="flex items-center gap-3 mb-4">
                <h3 class="text-6xl font-bold text-text-primary">{{ movie.title }}</h3>
                <span v-if="movie.isAi && showAiLabel" class="ai-badge">AI</span>
              </div>
              <div class="flex items-start gap-6 mb-6">
                <span class="text-warning font-bold text-xl flex-shrink-0">{{ movie.rating }}</span>
                <div v-if="movie.description" class="flex-1">
                  <p class="text-text-secondary text-lg leading-relaxed line-clamp-2">{{ movie.description }}</p>
                </div>
                <div v-else class="flex-1">
                  <p class="text-text-secondary text-lg leading-relaxed">暂无简介</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 指示点 -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUiStore } from '../../store/useUiStore'
import { storeToRefs } from 'pinia'
import KeenSlider from 'keen-slider'

// Props
interface Props {
  movies: any[]
}

const props = withDefaults(defineProps<Props>(), {
  movies: () => []
})

const router = useRouter()
const uiStore = useUiStore()
const { isSidebarCollapsed } = storeToRefs(uiStore)
const showAiLabel = computed(() => uiStore.showAiLabel)

const currentSlide = ref(0)
const sliderRef = ref<HTMLElement>()
let slider: any = null
let autoplayInterval: NodeJS.Timeout | null = null
let resizeObserver: ResizeObserver | null = null

const goDetail = (id: number) => {
  router.push({ name: 'MovieDetail', params: { id } })
}

const goToSlide = (index: number) => {
  if (slider) {
    slider.moveToIdx(index)
  }
}

// 初始化轮播
const initSlider = async () => {
  if (!sliderRef.value || props.movies.length === 0) return
  
  // 销毁现有slider
  if (slider) {
    slider.destroy()
  }
  
  // 等待DOM更新
  await nextTick()
  
  slider = new KeenSlider(sliderRef.value, {
    loop: true,
    mode: 'snap',
    slides: {
      perView: 1,
      spacing: 0,
    },
    dragSpeed: 0.8,
  }, [
    (slider) => {
      slider.on('slideChanged', () => {
        currentSlide.value = slider.track.details.rel
      })
    },
  ])
  
  // 启动自动轮播
  startAutoplay()
}

// 启动自动轮播
const startAutoplay = () => {
  // 清除现有定时器
  if (autoplayInterval) {
    clearInterval(autoplayInterval)
  }
  
  // 启动新的自动轮播
  autoplayInterval = setInterval(() => {
    if (slider && props.movies.length > 0) {
      slider.next()
    }
  }, 3500)
}

// 处理容器大小变化
const handleResize = async () => {
  if (slider && props.movies.length > 0) {
    // 重新计算轮播图尺寸
    slider.update()
  }
}

// 监听电影数据变化
watch(() => props.movies, async (newMovies) => {
  console.log('MovieCarousel movies changed:', newMovies)
  if (newMovies.length > 0) {
    // 调试：检查第一个电影的数据
    console.log('First movie data:', newMovies[0])
    console.log('First movie description:', newMovies[0]?.description)
    await initSlider()
  }
}, { immediate: true })

// 监听侧边栏状态变化
watch(isSidebarCollapsed, async () => {
  // 延迟一点时间让布局变化完成
  setTimeout(() => {
    handleResize()
  }, 300)
})

onMounted(async () => {
  if (props.movies.length > 0) {
    await initSlider()
  }
  
  // 设置 ResizeObserver 监听容器大小变化
  if (sliderRef.value) {
    resizeObserver = new ResizeObserver(() => {
      handleResize()
    })
    resizeObserver.observe(sliderRef.value)
  }
})

onUnmounted(() => {
  // 清理自动轮播定时器
  if (autoplayInterval) {
    clearInterval(autoplayInterval)
  }
  
  // 清理 ResizeObserver
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
  
  // 销毁slider
  if (slider) {
    slider.destroy()
  }
})
</script>

<style>
/* 全局keen-slider样式 */
.keen-slider {
  display: flex;
  overflow: hidden;
  position: relative;
  width: 100%;
  height: 100%;
}

.keen-slider__slide {
  flex-shrink: 0;
  height: 100%;
  position: relative;
  overflow: hidden;
  width: 100%;
}

/* 确保图片正确显示 */
.keen-slider__slide img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 文本截断样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style> 